package com.cn.fw4j.ioc;

import groovy.lang.GroovyObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import com.cn.fw4j.ioc.annotation.Fw4jDecorator;
import com.cn.fw4j.ioc.annotation.Fw4jIoc;
import com.cn.fw4j.ioc.annotation.Fw4jSpringIoc;
import com.cn.fw4j.ioc.impl.Fw4jSpringPlugs;
import com.cn.fw4j.ioc.inter.IFw4jSpringPlugs;
import com.cn.fw4j.util.ClassHelper;
import com.cn.fw4j.util.GroovyLoaderHelper;

public class ObjectHandle  {
	@SuppressWarnings("finally")
	public static Object newInstance(Class<?> cl){
		Object instance = null;
		try {
			instance = cl.newInstance();
			for(Field field : cl.getDeclaredFields()){
				Fw4jIoc ioc = field.getAnnotation(Fw4jIoc.class);
				Fw4jSpringIoc fsioc = field.getAnnotation(Fw4jSpringIoc.class);
				if(!field.isAccessible())
					field.setAccessible(true);
				if(ioc != null){
					Class<?> ic = Class.forName(ioc.value());
					field.set(instance, ObjectHandle.newInstance(ic));
				}else if(fsioc != null){
					IFw4jSpringPlugs ifsp = new Fw4jSpringPlugs();
					Object obj = ifsp.getBean(fsioc.value());
					field.set(instance, obj);
				}
			}
			return instance;
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			return instance;
		}
	}
	
	public static Object decorator(Method m,List<Object> args){
		    if(m != null){
				Fw4jDecorator dr = m.getAnnotation(Fw4jDecorator.class);
				if(dr != null){
					try {
						switch(dr.type().compareTo(dr.type())){
						case 0:
							Class<?> javaClass = ClassHelper.loadClass(dr.value());
							Method drm= ClassHelper.getMethod(javaClass.getMethods(), dr.method());
							return drm.invoke(javaClass.newInstance(), args.toArray());
						case 1:
							GroovyObject go = GroovyLoaderHelper.getInstance().getGroovyInstance(dr.value());
							return go.invokeMethod(dr.method(), args);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
		    }
		    return null;
	}
}
